package top.cross.webapp.common.mutilweb;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * create by Run
 * on 2020/7/29 13:57
 * do
 */
public class WebViewStartUtil {

    private static Class[] NOW = new Class[]{
            DivisionAAcitivity.class
//            , DivisionBAcitivity.class
//            , DivisionCAcitivity.class
//             ,DivisionDAcitivity.class
    };

    private static String[] NOW_PROCESSNAME = new String[]{
            "diviA"
//            , "diviB"
//            , "diviC"
//            ,"diviD"
    };

    private static Queue<String> appIds = new LinkedList<>();

    private static HashMap<String, WebProcess> appStacks = new HashMap<>();

    public static void start(Context context, String id, String url) {
        log("新进入 url = " + url);
        //如果找到已存在的
        WebProcess process = appStacks.get(id);
        if (process != null) {
            log("已找到 url = " + url);
            startActivity(context, process.clazz, id, url, false);
            return;
        }
        //如果没有，判断是否已经满了
        //如果没满，取一个没被使用的
        if (appIds.size() < NOW.length) {
            log("未满 开始查找");
            Collection<WebProcess> collection = appStacks.values();
            int pos = 0;
            for (int i = 0; i < NOW.length; i++) {
                int flag = -1;
                for (WebProcess webProcess : collection) {
                    if (NOW[i] == webProcess.clazz) {
                        flag = i;
                        break;
                    }
                }
                if (flag == -1) {
                    pos = i;
                    break;
                }
            }
            log("已找到未使用的 " + NOW_PROCESSNAME[pos]);
            WebProcess newIn = new WebProcess(NOW[pos], NOW_PROCESSNAME[pos], id, true);
            appIds.add(id);
            appStacks.put(id, newIn);
            startActivity(context, NOW[pos], id, url, true);
            return;
        }
        //如果已经满了，时间最早的一个
        String processId = appIds.poll();
        process = appStacks.remove(processId);
        log("已满 开始替换" + process.processName + " " + process.id);
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        log("试图杀死进程 " + context.getPackageName() + ":" + process.processName);
        manager.killBackgroundProcesses(context.getPackageName() + ":" + process.processName);
        WebProcess newIn = new WebProcess(process.clazz, process.processName, id, true);
        appIds.offer(id);
        appStacks.put(id, newIn);
        startActivity(context, newIn.clazz, id, url, true);
    }

    private static void startActivity(Context context, Class<? extends Activity> activity, String id, String url, boolean newLoad) {
//        if (newLoad) {
//            Intent intent = new Intent(context, activity);
//            intent.putExtra("id", id);
//            intent.putExtra("url", url);
//            intent.putExtra("newLoad", newLoad);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intent);
//        }
//        try {
//            Thread.sleep(500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Intent intent = new Intent(context, activity);
        intent.putExtra("id", id);
        intent.putExtra("url", url);
        intent.putExtra("newLoad", newLoad);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    static class WebProcess {
        Class<? extends Activity> clazz;
        String processName;
        String id;
        long time;
        boolean used = false;

        public WebProcess(Class<? extends Activity> clazz, String processName, String id, boolean used) {
            this.clazz = clazz;
            this.processName = processName;
            this.id = id;
            this.used = used;
            time = Calendar.getInstance().getTimeInMillis();
        }
    }

    private static void log(String msg) {
        Log.e("console", msg);
    }
}
